package com.coszero.utilslibrary.encryption;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * Desc： 散列/哈希加密
 * <p>
 *
 * @author ： xmqian
 * Email:xmqian93@163.com
 * Date: 2019/8/16 17:01
 * @version 1
 */
public class SHAUtils {
    /**
     * 进行sha1加密
     *
     * @param val 加密的字符串
     * @return
     * @throws NoSuchAlgorithmException
     */
    public static String getSHA(String val) throws NoSuchAlgorithmException {
        MessageDigest md5 = MessageDigest.getInstance("SHA-1");
        md5.update(val.getBytes());
        byte[] m = md5.digest();//加密
        return byte2hex(m);
    }

    private static String byte2hex(byte[] b) {
        String hs = "";
        String stmp = "";
        for (int n = 0; n < b.length; n++) {
            stmp = (Integer.toHexString(b[n] & 0XFF));
            if (stmp.length() == 1) {
                hs = hs + "0" + stmp;
            } else {
                hs = hs + stmp;
            }
        }
        return hs;
    }
}
